<template>
  <div class="stock-list">
    <button @click="show = true">添加唱片</button>
    <table>
      <tr>
        <th>序号</th>
        <th>唱片</th>
        <th>歌手</th>
        <th>价格</th>
        <th>库存</th>
        <th>操作</th>
      </tr>
      <tr v-for="(d, i) in list" :key="d.id">
        <td>{{ i + 1 }}</td>
        <td>{{ d.album }}</td>
        <td>{{ d.singer }}</td>
        <td>{{ d.price }}</td>
        <td>{{ d.number }}</td>
        <td>
          <button @click="$router.push('/stock/list/' + d.id)">查看详情</button>
        </td>
      </tr>
    </table>

    <add-modal v-if="show" @close="show = false" @add="add" />

    <router-view></router-view>
  </div>
</template>

<script>
import albumList from "./albumList";
import AddModal from "./AddModal.vue";
export default {
  components: { AddModal },
  data() {
    return {
      list: [],
      show: false,
    };
  },
  created() {
    // 没有值返回 null
    const storageList = localStorage.getItem("stock-list");
    const list = storageList ? JSON.parse(storageList) : albumList;
    this.list = list;
  },
  watch: {
    $route(newRoute, oldRoute) {
      console.log(newRoute, oldRoute, 1111);
      if (oldRoute.name === "stockDetail" && newRoute.name === "stockList") {
        const storageList = localStorage.getItem("stock-list");
        const list = storageList ? JSON.parse(storageList) : albumList;
        this.list = list;
      }
    },
  },
  methods: {
    add($event) {
      this.list.push({
        id: "ALBUM" + +new Date(),
        ...$event,
      });
      this.show = false;
      localStorage.setItem("stock-list", JSON.stringify(this.list));
    },
  },
};
</script>

<style lang="sass">
.stock-list
  table
    margin: 0 auto
    border-collapse: collapse
    td, th
      border: 1px solid #ccc
</style>
